package com.hontech.libratest.utils

import com.hontech.libratest.conn.Proto

class Frame(val dest: Int, val src: Int, val req: Int, val body: ByteArray) {

    companion object {

        fun make(dest: Int, req: Int, args: Array<SerialType>): ByteArray {
            var len = 10
            for (arg in args) {
                len += arg.size()
            }
            val buf = ByteArray(len)

            buf.encodeUInt16(0, Proto.Head)
            buf.encodeUInt16(2, len)
            buf.encodeUInt8(4, dest)
            buf.encodeUInt8(5, 0)
            buf.encodeUInt16(6, req)
            var index = 8
            for (arg in args) {
                arg.encode(buf, index)
                index += arg.size()
            }
            val s = buf.xorSum(8, index - 8)
            buf.encodeUInt8(index, s)
            buf.encodeUInt8(index + 1, Proto.End)
            return buf
        }

    }

    fun isNotify() = (req and Proto.NotifyFlag) != 0

    fun request(): Int {
        return req and ((Proto.NotifyFlag + Proto.SalveFlag).inv())
    }

    fun parse(args: Array<SerialType>) {
        var index = 0
        for (arg in args) {
            arg.decode(body, index)
            index += arg.size()
        }
    }

    override fun toString(): String {
        return "dest:$dest src:$src ${req.toHexStr4()}"
    }
}



